const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

console.log('WebSocket服务器运行在 ws://localhost:8080');

wss.on('connection', (ws) => {
    console.log('新客户端连接');

    ws.on('message', (data) => {
    console.log('收到消息:', data.toString());
    try {
        const message = JSON.parse(data.toString());
        // 检测客户端Ping并返回Pong
        if (message.type === 'ping' && message.source === 'client') {
            ws.send(JSON.stringify({
                type: 'pong',
                source: 'server',
                timestamp: new Date().toISOString()
            }));
            return;
        }
        // 如果是请求格式，添加响应标识
        if (message.requestId) {
            ws.send(JSON.stringify({
                ...message,
                response: true,
                timestamp: new Date().toISOString()
            }));
            return;
        }
        ws.send(data.toString());
    } catch {
        ws.send(data.toString());
    }
});

    ws.on('close', () => {
        console.log('客户端断开连接');
    });

    ws.on('error', (error) => {
        console.error('WebSocket错误:', error);
    });
});